package array;

/**
 * 统计数组中数量超过一半的数字
 *
 * 计数完了再验证
 */
public class CountThanMiddle {


  public int getNum(int[] array) {
    if (array == null || array.length == 0) {
      return -1;
    }
    //定义当前数字
    int result = array[0];
    //定义计数
    int count = 1;
    for (int i = 1; i < array.length; i++) {
      if (result == array[i]) {
        count++;
      } else {
        count--;
        if (count == 0) {
          result = array[i];
          count = 1;
        }
      }
    }

    if (!checkMoreThanHalf(result, array)) {
      result = -1;
    }

    return result;

  }

  private boolean checkMoreThanHalf(int result, int[] array) {
    boolean flag = false;
    int count = 0;
    for (int i = 0; i < array.length; i++) {
      if (result == array[i]) {
        count++;
      }
    }

    if (count * 2 > array.length) {
      flag = true;
    }

    return flag;

  }


  public static void main(String args[]) {
    int[] array = new int[]{1, 2, 3, 2, 2, 2, 5, 4, 2};
    CountThanMiddle countThanMiddle = new CountThanMiddle();
    int result = countThanMiddle.getNum(array);
    System.out.println(result);
  }
}
